from modules import *
import tkinter as tk
import tkinter.messagebox as msbox
import json
import subprocess
import os
import sys

sittings = json.dumps({})
try:
    with open(os.getcwd() + "/sittings.json", encoding='utf-8') as sittings:
        sittings = json.load(sittings) # Linux
except FileNotFoundError:
    try:
        with open(os.getcwd() + "\\sittings.json", encoding='utf-8') as sittings:
            sittings = json.load(sittings) # Windows
    except FileNotFoundError:
        msbox.showerror("Error!", "请检查sittings.json是否存在于目录下！")
        sys.exit(0)
    except Exception as ex:
        msbox.showerror(message=f"在读取sittings.json时出错！\n{ex}")
        sys.exit(0)
except Exception as ex:
    msbox.showerror(message=f"在读取sittings.json时出错！\n{ex}")
    sys.exit(0)



class GUI_root:
    def __init__(self) -> None:
        '''初始化'''
        self.__init__window()
        self.window.attributes(
            "-topmost", sittings["topmost"]
        )        # 是否永远在最顶端
        self.window.attributes(
            "-alpha", sittings["alpha"]
        )
        self.modules = []

    def __init__window(self):
        '''初始化窗口'''
        self.window = tk.Tk()
        self.window.title(sittings["title"])
        self.window.geometry(f"{sittings['size'][0]}x{sittings['size'][1]}")
        self.window.minsize(sittings['size'][0], sittings['size'][1])

        self.box = tk.Frame(self.window)

        self.__init__menubar()

    def __init__menubar(self):
        '''初始化菜单栏'''
        self.menubar = tk.Menu(
            self.window, relief=sittings["menu"]["relief"],
            font=sittings["menu"]["font"])

        self.__init__module()

        self.menubar.add_command(label="退出", command=self.__del__)

        self.sitbar = tk.Menu(self.menubar, tearoff=False)
        self.sitbar.add_command(label='打开sittings.json',
                                command=self._open_sitting_text)
        self.sitbar.add_command(label='关于', command=self.about)

        self.menubar.add_cascade(label='设置', menu=self.sitbar)

        self.window.config(menu=self.menubar)

    def __init__module(self):
        for i in sittings["module_list"]:
            self.menubar.add_command(
                label=i[0], command=self.__init__module__generator(i[1]))

    def __init__module__generator(self, module_name):
        '''读取模块'''
        def func():
            try:
                self.box.pack_forget()
                self.func.__del__()  # 清空
            except AttributeError:
                pass

            self.box = tk.Frame(self.window)
            self.func = eval(f"GUI_{module_name}(self.box,sittings)")
            self.box.pack(side=tk.TOP)

        return func

    def _open_sitting_text(self):
        try:
            os.startfile(os.getcwd() + "/sittings.json")
        except AttributeError:
            subprocess.call(["xdg-open", os.getcwd() + "/sittings.json"])

    def about(self):
        msbox.showinfo(
            title=sittings["version"], message=f"版权所有: Kinney08")

    def run(self):
        self.window.mainloop()

    def __del__(self):
        try:
            self.func.__del__()
        except:
            pass
        sys.exit(0)
